package com.xdwanj.criminalintent.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.xdwanj.criminalintent.R;
import com.xdwanj.criminalintent.pojo.Crime;
import com.xdwanj.criminalintent.viewmodel.CrimeDetailViewModel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class CrimeFragment extends Fragment implements DatePickerFragment.Callbacks {
    private static final String TAG = "CrimeFragment";

    private static final String ARG_CRIME_ID = "crimeId";
    private static final String DIALOG_DATE = "dialogDate";
    private static final String DATE_FORMAT = "EEE, MMM, dd";
    private static final int REQUEST_CONTACT = 1;

    private Crime crime;

    private EditText crimeTitleEditText;
    private Button dateButton;
    private CheckBox solvedCheckbox;

    private CrimeDetailViewModel crimeDetailViewModel;
    private Button reportButton;
    private Button suspectButton;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        crimeDetailViewModel = ViewModelProviders.of(this).get(CrimeDetailViewModel.class);
        crimeDetailViewModel = new ViewModelProvider(this).get(CrimeDetailViewModel.class);
        crime = new Crime();
        UUID crimeId = null;

        if (getArguments() != null)
            crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);

        crimeDetailViewModel.loadCrime(crimeId);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_crime, container, false);

        crimeTitleEditText = (EditText) view.findViewById(R.id.crime_title);
        dateButton = (Button) view.findViewById(R.id.crime_date);
        solvedCheckbox = (CheckBox) view.findViewById(R.id.crime_solved);
        reportButton = (Button) view.findViewById(R.id.crime_report);
        suspectButton = (Button) view.findViewById(R.id.crime_suspect);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        crimeDetailViewModel.crimeLiveData.observe(
                getViewLifecycleOwner(),
                crime -> {
                    if (crime != null) {
                        this.crime = crime;
                        updateUI();
                    }
                }
        );
    }

    private void updateUI() {
        Log.i(TAG, "updateUI: data is -> " + crime);
        crimeTitleEditText.setText(crime.getTitle());
        dateButton.setText(crime.getDate().toString());

        solvedCheckbox.setChecked(crime.isSoled());
        solvedCheckbox.jumpDrawablesToCurrentState();//跳过checkbox开始的的勾选动画

        if (crime.getSuspect() != null && crime.getSuspect().length() != 0) {
            suspectButton.setText(crime.getSuspect());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        if (requestCode == REQUEST_CONTACT && data != null) {
            Uri contactUri = data.getData();
            String[] queryFields = new String[]{ContactsContract.Contacts.DISPLAY_NAME};

            Cursor cursor = requireActivity()
                    .getContentResolver()
                    .query(contactUri, queryFields, null, null, null);

            if (cursor != null) {
                if (cursor.getCount() == 0) {
                    return;
                }

                cursor.moveToNext();
                String suspect = cursor.getString(0);
                crime.setSuspect(suspect);
                crimeDetailViewModel.saveCrime(crime);
                suspectButton.setText(suspect);
            }

            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private String getCrimeReport() {
        String solvedString = null;
        String dateString = null;
        String suspect = null;

        if (crime.isSoled()) {
            solvedString = getString(R.string.crime_report_solved);
        } else {
            solvedString = getString(R.string.crime_report_unsolved);
        }

        dateString = DateFormat.format(DATE_FORMAT, crime.getDate()).toString();

        if (crime.getSuspect() == null || crime.getSuspect().length() == 0) {
            suspect = getString(R.string.crime_report_no_suspect);
        } else {
            suspect = getString(R.string.crime_report_suspect, crime.getSuspect());
        }

        return getString(R.string.crime_report, crime.getTitle(), dateString, solvedString, suspect);

    }

    @Override
    public void onStart() {
        super.onStart();

        crimeTitleEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                crime.setTitle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        solvedCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> crime.setSoled(isChecked));

        dateButton.setOnClickListener(view -> {
            DatePickerFragment.newInstance(crime.getDate()).show(this.getChildFragmentManager(), DIALOG_DATE);
//            this.getChildFragmentManager() //上下一致
//                    .beginTransaction()
//                    .add(DatePickerFragment.newInstance(crime.getDate()), null)
//                    .addToBackStack(null)
//                    .commit();
        });

        reportButton.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_SENDTO)
                    .setType("text/plain")
                    .putExtra(Intent.EXTRA_TEXT, getCrimeReport())
                    .putExtra(Intent.EXTRA_SUBJECT, getString(R.string.crime_report_suspect));

            Intent chooser = Intent.createChooser(intent, getString(R.string.send_report));

            startActivity(chooser);
        });

        suspectButton.setOnClickListener(v -> {
            Intent pickContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(pickContactIntent, REQUEST_CONTACT);

            PackageManager packageManager = this.requireActivity().getPackageManager();

            ResolveInfo resolveInfo = packageManager.resolveActivity(pickContactIntent, PackageManager.MATCH_DEFAULT_ONLY);

            if (resolveInfo == null) {
                suspectButton.setEnabled(false);
            }
        });

    }

    @Override
    public void onStop() {
        super.onStop();
        crimeDetailViewModel.saveCrime(crime); //返回则保存
    }

    /**
     * <伪单例模式/>实例化CrimeFragment,将传入的数据绑定到 Bundle 中
     *
     * @param crimeId crime的id
     * @return CrimeFragment
     */
    public static CrimeFragment newInstance(UUID crimeId) {
        CrimeFragment crimeFragment = new CrimeFragment();

        //建议用这个对象传递数据,这个数据会被onCreate(Bundle)中的参数传递,数据可靠
        Bundle args = new Bundle();
        args.putSerializable(ARG_CRIME_ID, crimeId);
        crimeFragment.setArguments(args);
        return crimeFragment;
    }

    @Override
    public void onDateSelected(Date date) {
        crime.setDate(date);
        updateUI();
    }
}
